/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86136
 * Date: 2024-11-06
 * Time: 13:08
 */
public class HashBuck2<K,V> {
    static class Node<K,V> {
        public K key;
        public V val;
        public Node<K,V> next;
        public Node(K key,V val){
            this.key = key;
            this.val = val;
        }
    }
    public Node[] table = new Node[10];
    public int useSized;
    public static final double DEFAULT_LOAD_FACTOR = 0.75f;
    public void push(K key,V val) {
        //key是引用类型无法进行整型运算，通过获取hash值来确定下标index
        int hashCode = key.hashCode();
        int index = hashCode % table.length;
        Node cur = table[index];
        while(cur != null) {
            if(cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        Node node = new Node(key,val);
        node.next = table[index];
        table[index] = node;
        useSized++;
        if(doLoadFactor() >= DEFAULT_LOAD_FACTOR) {
            resize();
        }
    }

    private void resize() {
        //1.先实例化一个新的哈希表
        Node[] newTable = new Node[2*table.length];
        //2.遍历整个哈希表 将原哈希表中的节点放入新的哈希表中
        for (int i = 0; i < table.length; i++) {
            Node cur = table[i];
            while(cur != null) {
                int hashCode = cur.key.hashCode();
                int newIndex = hashCode % newTable.length;
                Node curN = cur.next;
                cur.next = newTable[newIndex];
                newTable[newIndex] = cur;
                cur = curN;
            }
        }
        //3.把新的哈希表赋给原哈希表
        table = newTable;
    }

    private double doLoadFactor() {
        return useSized*1.0 % table.length;
    }

    public V getVal(K key) {
        int hashCode = key.hashCode();
        int index = hashCode % table.length;
        Node<K,V> cur = table[index];
        while(cur != null) {
            if(cur.key.equals(key)) {
                return cur.val;
            }
            cur = cur.next;
        }
        return null;
    }
}
